package boot

import (
	"gitee.com/injoyai/goutil/lgs"
	"text/app"
	"github.com/go-redis/redis/v7"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"strings"
	"text/app/service/DaPing"
	"xorm.io/core"
)

func init() {
	//logs.AddFileHook("app")
	//连接数据库
	link := g.Cfg().GetString("database.link")
	app.TablePrefix = g.Cfg().GetString("database.tablePrefix", "text_")
	a := strings.Index(link, ":")
	driver := link[0:a]
	var err error
	app.DB, err = xorm.NewEngine(driver, link[a+1:])
	if err != nil {
		g.Log().Error(err)
		return
	}

	//设置表前缀和列名规则
	app.DB.SetTableMapper(core.NewPrefixMapper(core.SameMapper{}, app.TablePrefix))
	app.DB.SetColumnMapper(core.SameMapper{})
	//测试数据库连接
	//err = app.DB.Ping()
	//if err != nil {
	//	g.Log().Error(err)
	//	return
	//}

	r := g.Cfg().GetString("redis.default")
	app.RedisKeyPrefix = g.Cfg().GetString("redis.keyPrefix", "text_")
	v := strings.Split(r, ",")

	app.Redis = redis.NewClient(&redis.Options{
		Addr:     v[0],
		Password: v[2],            // no password set
		DB:       gconv.Int(v[1]), // use default DB
	})
	//_, err = app.Redis.Ping().Result()
	//if err != nil {
	//	g.Log().Error(err)
	//	return
	//}

	//其他初始化操作...
	lgs.PrintErr(app.DB.Sync2(
		new(DaPing.DaPingZuoBiao),        //坐标表
		new(DaPing.DaPingZuoBiaoLog),	//添加日志表
		new(DaPing.DaPingZuoVote),		//投票
	))
}
